from flask import render_template, request, redirect, flash, url_for, jsonify
from flask_login import login_required, current_user
from sqlalchemy import func

from app import app, db, modles
from app.utils.response_result import result, result_ok
from app.utils import MyCache


@app.route('/websites', methods=['GET'])
@login_required
def get_websites():
    """获取网站列表
    :return:
    """

    websites = modles.Website.query.all()

    return render_template('website/lists.html', websites=websites)


@app.route('/websites', methods=['POST'])
@login_required
def post_website():
    """添加一个website
    :return:
    """
    # if current_user.is_authenticated is False:

    username = current_user.username  # 获取当前用户

    form_data = request.form
    name = form_data['name']
    url = form_data['url']
    remark = form_data['remark']

    sort_id = form_data['sort_id']

    if not name or len(name) > 50:
        flash('网站名称不合法')
        return redirect(url_for('get_website', website_id=0))
    if not url or len(url) > 250:
        flash('网站地址不合法')
        return redirect(url_for('get_website', website_id=0))

    website = modles.Website(name=name, url=url, remark=remark, create_user=username, sort_id=sort_id)

    db.session.add(website)
    db.session.commit()

    return redirect(url_for('get_websites'))
    # return flask_ext.my_redirect('get_websites', request)


@app.route('/websites/<int:website_id>', methods=['GET'])
@login_required
def get_website(website_id: int):
    """根据 id 查询 一个网站

    :param website_id:
    :return:
    """
    website = modles.Website.query.filter_by(id=website_id).first()
    sorts = modles.WebsiteSort.query.filter_by(is_delete=0)

    return render_template('website/edit.html', website=website, sorts=sorts)


@app.route('/websites/<int:website_id>', methods=['POST', 'PUT', 'DELETE'])
@login_required
def put_website(website_id: int):
    """根据 id 更新/删除 一个网站
    :param website_id:
    :return:
    """

    _method = request.form['_method']

    website = modles.Website.query.filter_by(id=website_id).first()

    # 更新
    if _method == 'PUT':
        form_data = request.form;
        name = form_data['name']
        url = form_data['url']
        remark = form_data['remark']
        sort_id = form_data['sort_id']

        if not name or len(name) > 25:
            flash('名称输入无效')
            return redirect(url_for('get_website', sort_id=1))
        # 更新名称
        website.name = name
        website.url = url
        website.remark = remark
        website.sort_id = sort_id
        website.update_time = func.now()

        db.session.commit()  # 提交数据库会话
        flash('修改成功')
        return redirect(url_for('get_websites'))

    # 删除
    elif _method == 'DELETE':
        db.session.delete(website)
        db.session.commit()
        flash('删除成功')
        return redirect(url_for('get_websites'))
    else:
        flash('访问无效')
        return redirect(url_for('get_websites'))


@app.route('/api/websites/<int:website_id>/order', methods=['PUT'])
def put_website_order(website_id):
    """点赞(排序)
    :param website_id:
    :return:
    """
    # 根据请求ip + url 缓存
    if MyCache.has(request.remote_addr + request.path):
        return result(4060, "你已经投过票了")

    website = modles.Website.query.filter_by(id=website_id).first()
    website.order = website.order + 1
    db.session.commit()

    return result_ok()
